Component({
  properties: {
    item: {
      type: Object,
      value: {}
    },
    index: {
      type: Number,
      value: 0
    }
  },

  data: {
    score: 0,
    comment: '',
    photos: [],
    showComment: false
  },

  lifetimes: {
    attached() {
      // 初始化得分为满分
      this.setData({
        score: this.properties.item.maxScore || 0
      });
    }
  },

  methods: {
    // 滑块改变分数
    onScoreChange(e) {
      const score = e.detail.value;
      this.setData({ score });
      this.triggerScoreChange();
    },

    // 输入框改变分数
    onScoreInput(e) {
      let score = parseInt(e.detail.value || 0);
      // 确保分数不超过最大值
      if (score > this.properties.item.maxScore) {
        score = this.properties.item.maxScore;
      }
      this.setData({ score });
      this.triggerScoreChange();
    },

    // 触发分数变化事件
    triggerScoreChange() {
      this.triggerEvent('scorechange', {
        index: this.properties.index,
        itemId: this.properties.item._id,
        score: this.data.score,
        comment: this.data.comment,
        photos: this.data.photos
      });
    },

    // 显示/隐藏评语输入框
    showCommentInput() {
      this.setData({
        showComment: !this.data.showComment
      });
    },

    // 评语输入
    onCommentInput(e) {
      this.setData({
        comment: e.detail.value
      });
      this.triggerScoreChange();
    },

    // 拍照功能
    takePhoto() {
      const that = this;
      wx.chooseImage({
        count: 9 - that.data.photos.length,
        sizeType: ['compressed'],
        sourceType: ['camera', 'album'],
        success(res) {
          // 将新拍摄的照片添加到数组中
          const newPhotos = that.data.photos.concat(res.tempFilePaths);
          that.setData({
            photos: newPhotos
          });
          that.triggerScoreChange();
        }
      });
    },

    // 预览图片
    previewImage(e) {
      const index = e.currentTarget.dataset.index;
      wx.previewImage({
        current: this.data.photos[index],
        urls: this.data.photos
      });
    },

    // 删除照片
    deletePhoto(e) {
      const index = e.currentTarget.dataset.index;
      const photos = this.data.photos;
      photos.splice(index, 1);
      this.setData({ photos });
      this.triggerScoreChange();
    }
  }
});